package com.wiloon.java8x.database;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/**
 * Created by wiloon on 1/17/16;
 */
public class JdbcInsert {
    private static Logger logger = LoggerFactory.getLogger(JdbcInsert.class);
    public static void main(String[] args) {

        Connection conn=getConn( );
        String sql ="insert into test_insert (name,email) values('nameStr','emailStr')";
        int count = 100000 ;
        int commitPoint=10000;
        try {
            PreparedStatement prest = conn.prepareStatement(sql);
            long a=System.currentTimeMillis();
            for(int x = 1; x <= count; x++){

               // prest.execute();
                prest.executeUpdate();
                if(x%commitPoint==0){
                    conn.commit();
                }
            }
            long b=System.currentTimeMillis();
            logger.debug("count:{}",count);
            logger.debug("start:{}",a);
            logger.debug("end:{}",b);
            logger.debug("b-a:{}",b-a);
            logger.debug("qps:{}",count/((b-a)/1000));
            conn.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }finally{

        }

    }

    /**
     * 创建连接
     * @return
     */
    public static Connection getConn( ){
        long a=System.currentTimeMillis();
        try {

            String mySqlUrl="jdbc:mysql://127.0.0.1:3306/test";
            String mySqlUserName="user0";
            String mySqlPassword="password0";

                Class.forName("com.mysql.jdbc.Driver");
                Connection conn =  DriverManager.getConnection(mySqlUrl, mySqlUserName, mySqlPassword);
                conn.setAutoCommit(false);
                return conn;

        } catch (Exception ex) {
            ex.printStackTrace();
        }finally{
            long b=System.currentTimeMillis();
            System.out.println("创建连接用时"+ (b-a)+" ms");
        }
        return null;
    }
}
